<template>
<div>
  <el-table
    v-table-style
    header-row-class-name="base-table-header-v3"
    :row-class-name="getRowClass"
    class="material-card-table"
    v-loading="listLoading"
    :data="disposeFormListViewTime(data, columns)"
    border
    @selection-change="handleSelectionChange">

    <template slot="empty">
      <BaseListForNoData
        v-show="!listLoading"
        table-type="smallTable"
        :notice-msg="$t('common.base.tip.noData')"
      ></BaseListForNoData>
    </template>

    <el-table-column type="selection" align="center" width="48"></el-table-column>

    <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
    
    <!-- start 展开行 -->
    <el-table-column type="expand" width="50" v-if="showExpand">
      <template slot-scope="scope">
        <template v-if="scope.row.outWarehouseFlowExtras && scope.row.outWarehouseFlowExtras.length">
          <div class="records-title">{{$t('task.detail.components.stockInfo')}}</div>
          <material-apply-records 
            type="out"
            :data="scope.row.outWarehouseFlowExtras" 
            :columns="outWarehouseColumns"
            :logistics-data="logisticsData"
            :is-look-repertory-record-info="isLookRepertoryRecordInfo"
            @getLogisticsMessage="getLogisticsMessage" />
        </template>
        
        <template v-if="scope.row.backorderWarehouseList && scope.row.backorderWarehouseList.length">
          <div class="records-title">{{$t('task.detail.components.lackStockInfo')}}</div>
          <material-apply-records 
            type="lack"
            :data="scope.row.backorderWarehouseList" 
            :is-look-repertory-record-info="isLookRepertoryRecordInfo"
            :columns="backorderWarehouseColumns"/>
        </template>
        
        <template v-if="scope.row.paasApproveList && scope.row.paasApproveList.length">
          <div class="records-title">{{$t('task.detail.components.materialApprove')}}</div>
          <material-apply-records 
            :data="scope.row.paasApproveList" 
            :is-look-repertory-record-info="isLookRepertoryRecordInfo"
            :columns="paasApproveList"/>
        </template>
        
      </template>
    </el-table-column>
    <!-- end 展开行 -->

    <template v-for="column in columns">
    <el-table-column
      :key="column.fieldId"
      v-if="column.show"
      :label="column.displayName"
      :prop="column.fieldName"
      show-overflow-tooltip
      :min-width="column.minWidth || '100px'"
      :fixed="column.fixed">
      <template slot-scope="scope">
        <!-- start 预计用量 -->
        <template v-if="column.fieldName === 'preNum' && !isWarrantyConfirmation">
          <template v-if="!scope.row.editable">
            <span>{{ scope.row[column.fieldName] }}</span>
            <i class="iconfont icon-edit-square" @click="editPreNum(scope.row, scope.$index)" v-if="allowEdit"></i>
          </template>

          <template v-else>
            <input
              type="number"
              v-model="scope.row.preNum"
              @change="handlePreNum(scope.row, scope.$index)"
              @blur="togglePreNumEditable(scope.row, scope.$index)"
            />
          </template>
        </template>
        <!-- end 预计用量 -->
        
        <!-- 创建人 -->
        <template v-else-if="column.fieldName === 'createUser'">
          <template v-if="isOpenData && scope.row.createUserStaffId">
            <open-data type='userName' :openid="scope.row.createUserStaffId"></open-data>
          </template>
          <template v-else>
            {{ scope.row.createUserName }}
          </template>
        </template>

        <!-- 规格 -->
        <template v-else-if="column.fieldName === 'standard'">
          {{ scope.row.materialStandard }}
        </template>

        <!-- 类别 -->
        <template v-else-if="column.fieldName === 'type'">
          {{ scope.row.materialType }}
        </template>

        <!-- 状态 -->
        <template v-else-if="column.fieldName === 'materialStatus'">
          {{ scope.row.materialStatus ? $t('common.base.open') : $t('common.base.disable') }}
        </template>

        <!-- start 已申领数量 -->
        <template v-else-if="column.fieldName === 'applyNum'">
          {{ scope.row[column.fieldName] || 0 }}
        </template>
        <!-- end 已申领数量 -->

        <!-- start 单价 -->
        <template v-else-if="column.fieldName === 'salePrice'">
          {{ scope.row | fmt_salePrice_currency }} 
        </template>
        <!-- end 单价 -->

        <!-- start 小计 -->
        <template v-else-if="column.fieldName === 'total'">
          {{ scope.row | fmt_total_currency }} 
        </template>
        <!-- end 小计 -->

        <template v-else-if="column.fieldName === 'warrantyStatus'">
          {{ warrantyStatusMap[scope.row.warrantyStatus] }}
        </template>

        <!-- 批次号 -->
        <template v-else-if="column.fieldName === 'batchNumber'">
          <span>{{ scope.row.batchNumber ? scope.row.batchNumber : scope.row.batchNumberList && scope.row.batchNumberList.join()  }}</span>
        </template>

        <!-- 富文本 -->
        <template v-else-if="column.formType === 'richtext'">
          <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
            <span v-if="scope.row.attribute[column.fieldName]">{{$t('common.base.view')}}</span>
          </div>
        </template>

        <template v-else>
          {{ $formatFormField(column, scope.row) }}
        </template>
      </template>
    </el-table-column>
    </template>

    <el-table-column fixed="right" :label="$t('common.fields.action.displayName')" width="100" v-if="allowDelete">
      <template slot-scope="scope">
        <el-button
          class="text-danger"
          type="text"
          size="mini"
          @click="deleteMaterial(scope.row, scope.$index)"
        >{{$t('common.base.delete')}}</el-button>
      </template>
    </el-table-column>
  </el-table>
  
  <!-- 底部数据量统计 -->
  <div class="table-footer">
    <i18n path="common.base.table.totalCount">
      <span place="count" class="level-padding">{{data.length || 0}}</span>
    </i18n>
  </div>
  
  <!-- 富文本弹窗 -->
  <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
</div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi';
import * as WareHouseApi from '@src/api/WareHouseApi'

/* util */
import { isOpenData } from '@src/util/platform';
import MathUtil from '@src/util/math';
import { getRootWindow } from '@src/util/dom';
/* components */
import MaterialApplyRecords from './MaterialApplyRecords';
/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
/* model */
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()

export default {
  name: 'material-card-list',
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    listLoading: {
      type: Boolean,
      default: false
    },
    materialConfig: {
      type: Object,
      default: () => ({})
    },
    allowEdit: {
      type: Boolean,
      default: false
    },
    allowDelete: {
      type: Boolean,
      default: false
    },
    card: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      isOpenData,
      multipleSelection: [],
      logisticsData: {},
      warrantyStatusMap: {
        0: this.$t('common.base.warranty'),
        1: this.$t('common.base.surrender')
      }
    }
  },
  computed: {
    // 显示展开行
    showExpand() {
      return this.data.some(item => item.outWarehouseFlowExtras.length > 0 || item.backorderWarehouseList.length > 0 || item.paasApproveList?.length > 0)
    },
    /** 物料清单附加组件配置 */
    cardConfig() {
      return JSON.parse(this.card.config || '{}');
    },
    /** 
    * @description 允许通过工单查看物料出入库详情
    */
    isLookRepertoryRecordInfo() {
      // let { isLookRepertoryRecordInfo } = this.cardConfig;
      // return isLookRepertoryRecordInfo

      // 以前是通过上面的变量控制的，后面根据后端的要求，修复bug22217,直接去掉了该限制，所以我在次直接写死了true，默认就是任何时候，物料申领下面的单据都能展示超链接，允许用户跳转。
      return true
    },

    /** 
    * @description 限制修改物料数量功能的灰度
    */
    isWarrantyConfirmation() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.warrantyConfirmation || false
    },

    // task-detail-card
    outWarehouseColumns() {
      return [
        {
          displayName: this.$t('common.fields.outboundNumber.displayName'),
          fieldName: 'bizId',
          minWidth: '140px'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum9'),
          fieldName: 'warehouseName'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum12'),
          fieldName: 'warehousePositionName'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum15'),
          fieldName: 'stateDict'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum16'),
          fieldName: 'logisticsNo'
        },
        {
          displayName: this.$t('common.form.preview.sparepart.colum17'),
          fieldName: 'typeName'
        },
        {
          displayName: this.$t('common.base.createUser'),
          fieldName: 'createUserName',
          minWidth: '110px'
        }, 
        {
          displayName: this.$t('common.base.createTime'),
          fieldName: 'createTime',
          minWidth: '150px'
        }
      ]
    },
    backorderWarehouseColumns() {
      return [
        {
          displayName: this.$t('common.form.preview.sparepart.colum18'),
          fieldName: 'documentsId',
          minWidth: '140px'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum9'),
          fieldName: 'warehouseName'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum12'),
          fieldName: 'positionName'
        }, 
        {
          displayName: this.$t('common.base.state'),
          fieldName: 'stateDict'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum19'),
          fieldName: 'flag',
          minWidth: '140px'
        },
        {
          displayName: this.$t('common.base.createTime'),
          fieldName: 'createTime',
          minWidth: '150px'
        }
      ]
    },
    paasApproveList() {
      return [
        {
          displayName: this.$t('common.form.preview.sparepart.colum18'),
          fieldName: 'paasApproveNo',
          minWidth: '140px'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum20'),
          fieldName: 'applyNum'
        }, 
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel7'),
          fieldName: 'warranty'
        }, 
        {
          displayName: this.$t('common.base.state'),
          fieldName: 'status'
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum21'),
          fieldName: 'opinion',
          minWidth: '140px'
        },
        {
          displayName: this.$t('common.base.createTime'),
          fieldName: 'createTime',
          minWidth: '150px'
        }
      ]
    },
  },
  methods: {
    disposeFormListViewTime,
    /** 
    * @description 删除物料
    */
    async deleteMaterial(row, index) {
      // 判断是否存在待审批的记录
      const warningMsg = row.suspendingFlag ? this.$t('task.tip.deleteMaterialTip2') : this.$t('task.tip.deleteTip');

      let result = await this.$platform.confirm(warningMsg);
      if (!result) return;

      // 缺货单据id
      let materialBackorderIds = row?.backorderWarehouseList.map(item => item.id)
      let params = {
        inventoryId: row.id,
        materialBackorderIds
      }
      
      TaskApi.deleteByInventory(params) // 对接时更换接口
        .then(res => {
          if (res.success) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.deleteSuccess')
            })

            this.data.splice(index, 1);
            // 更新动态信息
            this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord)
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },
    /**
    * @description 点击编辑预计用量
    */
    editPreNum(row, index) {
      // 备份预计用量数据
      row.backupNum = row.preNum;

      this.togglePreNumEditable(row, index);
    },
    /**
    * @description 修改预计用量
    */
    handlePreNum(item, index) {
      let value = Number(item.preNum);
      let count = this.decimalNumber(value);

      if (value <= 0) {
        this.$platform.alert(this.$t('task.tip.rightNumTip'));
        item.preNum = item.backupNum;
        return;
      }

      if (value < item.applyNum) {
        this.$platform.alert(this.$t('task.tip.preNumTip1'));
        item.preNum = item.backupNum;
        return;
      }

      if (value > PART_SERVICE_LIST_PRENUM_MAX_LENGTH) {
        this.$platform.alert(`${this.$t('common.base.estimate')} ${PART_SERVICE_LIST_PRENUM_MAX_LENGTH_MESSAGE}`);
        item.preNum = item.backupNum;
        return;
      }
      
      if (count != -1 && count == 0) {
        this.$platform.alert(this.$t('task.tip.greaterThanZeroTip1'));
        item.preNum = item.backupNum;
        return;
      }
      
      if (count != -1 && count != 0) {
        this.$platform.alert(this.$t('task.tip.greaterThanZeroTip2', {count}));
        item.preNum = item.backupNum;
        return;
      }

      // 去掉多余0
      item.preNum = item.preNum.replace(/(?:\.0*|(\.\d+?)0+)$/, '$1');

      TaskApi.putTaskInventoryValue({id: item.id, preNum: item.preNum, type: 3})
        .then(res => {
          if (res.success) {
            item.backupNum = item.preNum;
            item.total = (item.preNum * item.salePrice).toFixed(2);
            // 可申领数据 = 预计用量 - 已申领数量 重新计算一下可申领，不然子组件拿不到最新的数据。
            item.allowNum = item.preNum - item.applyNum;
          } else {
            this.$platform.alert(res.message);
          }
        }).catch(err => console.error(err))
    },
    /**
    * @description 预计用量小数位
    */
    decimalNumber(num) {
      let precision = 0
      let count = MathUtil.decimalNumber(num);

      if(count != 0) return 0;
      if(precision >= count) return -1;
      return precision;
    },
    /** 
    * @description 更新预计用量是否可编辑状态
    */
    togglePreNumEditable(row, index) {
      this.$set(row, 'editable', !row.editable);
    },
    getRowClass(item) {
      // 无申请记录时隐藏展开行按钮
      if (!item.row.outWarehouseFlowExtras?.length && !item.row.backorderWarehouseList?.length
        && !item.row.paasApproveList?.length
      ) return 'base-table-row-v3 row-expand-cover';
      return 'base-table-row-v3';
    },
    handleSelectionChange(value) {
      this.multipleSelection = value
    },
    /**
    * @description 获取物流信息
    */
    getLogisticsMessage(value) {
      let param = {
        logisticsNo: value,
        companyType: ''
      }
      WareHouseApi.getWarehouseFlowLogistics(param)
        .then(res => {
          if (res.success) {
            this.logisticsData = res.data || []
          } else {
            this.$platform.alert(res.message)
          }
        }).catch(err => console.error(err))
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false, true);
    }
  },
  components: {
    [MaterialApplyRecords.name]: MaterialApplyRecords
  }
}
</script>

<style lang="scss">
.material-card-table {
  border-top: 1px solid #ebeef5;

  .row-expand-cover {
    .el-table__expand-icon  {
      display: none;
    }
  }

  .base-table-row-v3 td {
    position: inherit;

    .el-button {
      min-width: auto !important;
      padding: 0;
    }
  }

  .icon-edit-square {
    margin-left: 8px;
    vertical-align: middle;

    &:hover {
      color: $color-primary;
      cursor: pointer;
    }
  }

  .records-title {
    padding: 10px 0;
  }
}
</style>

<style lang="scss" scoped>
::v-deep .el-table__expanded-cell {
  padding: 0 0 6px 40px;
  background: $bg-color-l1;

  &:hover {
    background: $bg-color-l1 !important;
  }
}

::v-deep .el-checkbox {
  margin-bottom: 0;
}

input[type="number"] {
  width: 99%;
}

.material-card-table {
  ::v-deep .el-table__fixed-right {
    .el-table__fixed-body-wrapper {
      .el-table__expanded-cell {
        visibility: hidden;
        padding: 0;
        background-color: #fff;
      }
    }
    
  }
}
</style>
